﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    public partial class CreateOtherStockDecreaseBillView : UserControl, IView
    {
        Promise _promise = new Promise();
        List<WebRef.EStockDecreaseBillItem> listItem = new List<WebRef.EStockDecreaseBillItem>();
        /// <summary>
        /// 领料人
        /// </summary>
        Common.Validations.SearchLookUpEditValidation _searchLookUpEditValidation;
        public CreateOtherStockDecreaseBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlSearchLookUpEditStockDecreaseType, "出库类型"));
            _searchLookUpEditValidation = new Common.Validations.SearchLookUpEditValidation(this.selectLupPicker, "领料人");
            ValidationManager.Register(this, _searchLookUpEditValidation);
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtRemark, "出库备注", true));
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("ok", Resources.isOK, "保存", btnSave_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", btnCancel_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise
                .Then(() =>
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        ctlSearchLookUpEditStockDecreaseType.BindIntCodeTextItem(Domain.Constant.StockChangeTypes.EnumerateDecrease(), null, true);
                        _promise.Resolve();
                    }));
                }).Then(() =>
                {
                    selectLupPicker.BindVStaffPosition(_promise, Domain.Constant.StaffPosts.SalesManager);
                })
               .Run();
        }

        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.ActiveArgs != null)
                {
                    if (args.ClosedArgs.View is Pickers.MaterialStockPicker)
                    {
                        BindStockDecreaseBillItem(args);
                    }
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("");
        }
        #endregion

        #region Method
        /// <summary>
        /// 绑定选择的商品列表
        /// </summary>
        /// <param name="args"></param>
        private void BindStockDecreaseBillItem(ViewResumeArgs args)
        {
            WebRef.VStockMaterial item = args.ClosedArgs.Data as WebRef.VStockMaterial;
            if (item != null)
            {
                WebRef.EStockDecreaseBillItem stockItem = new WebRef.EStockDecreaseBillItem(
                    item.WarehouseId,
                    item.WarehouseName,
                    item.Id,
                    item.Name,
                    item.StockCount);
                stockItem.Count = 1;
                stockItem.Price = item.Price;
                if (listItem.Exists((WebRef.EStockDecreaseBillItem s) =>
                    s.MaterialId == item.Id && s.WarehouseId == item.Id ? true : false))
                {
                    UIContext.Current.ViewManager.ShowWarning("此仓库下的此商品已添加过，不能重复添加！");
                }
                else
                {
                    listItem.Add(stockItem);
                }
            }
            this.GCData.DataSource = null;
            this.GCData.DataSource = listItem;
        }
        /// <summary>
        /// 获取选择的出库类型
        /// </summary>
        /// <returns></returns>
        private Domain.IntCodeTextItem GetSelectStockType()
        {
            return this.ctlSearchLookUpEditStockDecreaseType.GetSelectedValue<Domain.IntCodeTextItem>();
        }
        /// <summary>
        /// 获取选择的领料人
        /// </summary>
        /// <returns></returns>
        private WebRef.VStaffPosition GetSelectPicker()
        {
            return this.selectLupPicker.EditValue as WebRef.VStaffPosition;
        }
        /// <summary>
        /// 获取选择的出库商品列表
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EStockDecreaseBillItem> GetDecreaseBillItem()
        {
            List<WebRef.EStockDecreaseBillItem> list = this.GCData.DataSource as List<WebRef.EStockDecreaseBillItem>;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Count <= 0)
                {
                    UIContext.Current.ViewManager.ShowWarning("出库数量应大于0！");
                    return null;
                }
                if (list[i].Count > list[i].StockCount)
                {
                    UIContext.Current.ViewManager.ShowWarning("出库数量大于此商品库存数量！");
                    return null;
                }
            }
            return list;
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        private bool ValidateData()
        {
            if (GetSelectStockType() == Domain.Constant.StockChangeTypes.DecreaseRequisitionItem)
            {
                ValidationManager.Unregister(this, _searchLookUpEditValidation);
            }
            string strMess = null;
            if (!ValidationManager.Validate(this, out strMess))
            {
                UIContext.Current.ViewManager.ShowWarning(strMess);
                return false;
            }
            if (listItem.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择出库商品！");
                return false;
            }
            if (GetDecreaseBillItem() == null)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 创建出库单
        /// </summary>
        private void CreateDecreaseBill()
        {
            WebRef.EStockDecreaseBill bill = new WebRef.EStockDecreaseBill();
            if (GetSelectStockType() == Domain.Constant.StockChangeTypes.DecreaseRequisitionItem)
            {
                bill.Handler = GetSelectPicker().StaffId;
                bill.HandledTime = DateTime.Now;
            }
            bill.Type = GetSelectStockType().Code;
            bill.Memo = this.txtRemark.Text.Trim();
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateStockDecreaseBill(bill, GetDecreaseBillItem().ToArray());
                this.BeginInvoke(new Action<ServiceResult>((p) =>
                {
                    this.HideMask();
                    if (p.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                    }
                }), result);
            });
        }
        #endregion

        #region Action
        private void btnAddStock_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.MaterialStockPicker(), new PopupViewArgs("选择商品"));
        }
        /// <summary>
        /// 清除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEditOperate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "移除")
            {
                if (this.GVData.FocusedRowHandle > -1)
                {
                    WebRef.EStockDecreaseBillItem item = this.GVData.GetFocusedRow() as WebRef.EStockDecreaseBillItem;
                    listItem.Remove(item);
                    if (listItem.Count == 0)
                    {
                        this.GCData.DataSource = null;
                    }
                    else
                    {
                        this.GCData.DataSource = null;
                        this.GCData.DataSource = listItem;
                    }
                }
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, object e)
        {
            if (ValidateData())
            {
                CreateDecreaseBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 领料出库时显示领料人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlSearchLookUpEditStockDecreaseType_EditValueChanged(object sender, EventArgs e)
        {
            if (GetSelectStockType() == Domain.Constant.StockChangeTypes.DecreaseRequisitionItem)
            {
                lblPicker.Visible = true;
                this.selectLupPicker.Visible = true;
            }
            else
            {
                lblPicker.Visible = false;
                this.selectLupPicker.Visible = false;
            }
        }
        private void GVData_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (this.GVData.FocusedColumn == e.Column)
            {
                if (e.Column.FieldName == "Count")
                {
                    WebRef.EStockDecreaseBillItem model = this.GVData.GetRow(e.Column.View.FocusedRowHandle) as WebRef.EStockDecreaseBillItem;
                    this.GVData.SetRowCellValue(e.Column.View.FocusedRowHandle, "Amount", model.Amount);
                }
            }
        }
        #endregion
    }
}
